import 'package:flutter/material.dart';
import 'package:xlsk/utils/dimension.dart';
import 'package:xlsk/utils/colorGradient.dart';

class TabSwiper extends StatefulWidget {
  double width;
  double swiperWidth;
  double dx;
  double old_dx = 0;
  List<Map<String,dynamic>> list;
  double lineDx = 0;
  double lineAddDx = 0;
  int current = 0;
  var onClick;
  List<dynamic> colorGradientArr = ColorGradient().createGradient(startColor:'#303133',endColor:'#1661FF');
  String nowTabColor = '#303133';
  String nextTabColor = '#1661FF';
  String direction = '';

  TabSwiper({
    Key ?key,
    required this.width,
    required this.list,
    required this.swiperWidth,
    required this.dx,
    required this.onClick,
    this.current = 0,
  }):super(key: key);

  @override
  State<StatefulWidget> createState() {
    return _tabswiperState();
  }
}

class _tabswiperState extends State<TabSwiper> {
  late double lineDx = 0;
  double old_dx = 0;
  String direction = '';


  @override
  void initState() {
    super.initState();
    lineDx = widget.width/widget.list.length/2*(widget.current + 1) - 16/2;
    Future.delayed(Duration.zero, () {
      //执行代码写在这里
      // init();
    });
  }

  @override
  Widget build(BuildContext context) {
    setDx(widget.dx);
    setTabColor(widget.dx);

    return Container(
      width: widget.width,
      height: Dimension(context).toPx(40),
      color: Colors.white,
      child: Stack(
        children: [
          renderList(),
          Positioned(
            bottom: Dimension(context).toPx(2),
            left: lineDx + widget.lineAddDx,
            child: Container(
              width: Dimension(context).toPx(16),
              height: Dimension(context).toPx(4),
              decoration: BoxDecoration(
                color: Color(0xFF1661FF),
                borderRadius: BorderRadius.all(Radius.circular(Dimension(context).toPx(4))),
                gradient: new LinearGradient(
                  begin: const Alignment(-1, 0),
                  end: const Alignment(1, 0),
                  colors: [
                    const Color(0xff1661ff),
                    const Color.fromRGBO(22, 97, 255, 0)
                  ]
                )
              ),
            ),
          ),
        ],
      ),
    );
  }

  void init(){
    countLineDx();
  }

  // 位移
  setDx(dx){
    // 两个tab之间的距离等于一个tab的宽度
    double distanceX = widget.width/widget.list.length;
    setState(() {
      widget.lineAddDx = (dx / widget.swiperWidth) * distanceX;
    });
    // 判断方向
    // print('${old_dx},${dx},${direction}');
    if(old_dx < dx){
      direction = 'right';
    }else if(old_dx > dx){
      direction = 'left';
    }
    old_dx = dx;
  }

  setTabColor(dx){
    int colorIndex = ((dx / widget.swiperWidth) * 100).ceil().abs();
    int colorLength = widget.colorGradientArr.length;
    List<Map<String,dynamic>> list = widget.list;
    // 处理超出索引边界的情况
    colorIndex = colorIndex >= colorLength ? colorLength - 1 : colorIndex <= 0 ? 0 : colorIndex;
    // 设置下一个tab的颜色
    int nextCurrent = 0;
    int nowCurrent = 0;
    if(direction == 'right'){
      nextCurrent = (dx/widget.swiperWidth).ceil();
      nowCurrent = nextCurrent - 1;
    }else if(direction == 'left'){
      nextCurrent = (dx/widget.swiperWidth).floor();
      nowCurrent = nextCurrent + 1;
      colorIndex = 99 - colorIndex;
    }
    list[nextCurrent]['color'] = widget.colorGradientArr[colorIndex];
    list[nowCurrent]['color'] = widget.colorGradientArr[colorLength - 1 - colorIndex];
    // print('${widget.colorGradientArr[colorIndex]},${widget.colorGradientArr[colorLength - 1 - colorIndex]},${nextCurrent},${nowCurrent},${colorIndex}');
    setState(() {
      widget.list = list;
    });
  }

  // 计算滑块最终要停留的位置
  countLineDx(){
    int length = widget.list.length;
    bool tab = length >= widget.current + 1;
    if(tab){
      setState(() {
        lineDx = widget.width/length/2*(widget.current + 1) - 16/2;
      });
    }
  }

  Widget renderList(){
    List<Widget> list = [];
    widget.list.asMap().keys.map((index){
      Widget content = GestureDetector(
        behavior: HitTestBehavior.opaque,
        onTap: (){
          widget.onClick(index);
        },
        child: Container(
          width: Dimension(context).toVw(100/widget.list.length),
          height: Dimension(context).toPx(40),
          child: Center(
            child: Text('${widget.list[index]['title']}',style: TextStyle(fontSize: Dimension(context).toPx(15),color: Color(widget.list[index]['color']))),
          ),
        ),
      );
      list.add(content);
    }).toList();
    Widget view = Row(
      children: list,
    );
    return view;
  }

  @override
  void dispose() {
    super.dispose();
  }
}
